#include <string.h>
#include <stdlib.h>
#include "discountLoad.h"
int loadDiscounts(char const * filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"r");
	if(!ptr_file){
		return 1;
	}
	int maxlinelen;
	int numlines=getFileInfo(ptr_file,&maxlinelen);
	discountdata=(struct DiscountVars*) calloc(numlines,sizeof(struct DiscountVars));
	char *buf=(char*) malloc(maxlinelen*sizeof(char));
	for(int i=0;i<numlines;i++){
		fgets(buf,maxlinelen,ptr_file);//load line into buffer;
		strcpy(discountdata[i].id,strtok(buf,"/"));
		strcpy(discountdata[i].desc,strtok(NULL,"/"));
		strcpy(discountdata[i].type,strtok(NULL,"/"));
		strcpy(discountdata[i].status,strtok(NULL,"/"));
		discountdata[i].amount=(int)*strtok(NULL,"/");
		strcpy(discountdata[i].applicability,strtok(NULL,"/"));
	}
	fclose(ptr_file);
	return 0;
}

int writeDiscounts(char const *filename){
	FILE *ptr_file;
	ptr_file=fopen(filename,"w");
	if(!ptr_file){
		return 1;
	}
	for(int i=0;i<discountcount;i++){
		fprintf(ptr_file,"%s/%s/%s/%s/%d/%s\n",discountdata[i].id,discountdata[i].desc,discountdata[i].type,discountdata[i].status,discountdata[i].amount,discountdata[i].applicability);
	}
	fclose(ptr_file);
	free(discountdata);
	return 0;
}

void addDiscount(struct DiscountVars n){
	discountdata=(struct DiscountVars*) realloc(discountdata,++discountcount*sizeof(struct DiscountVars));
	discountdata[discountcount-1]=n;
}

void rmDiscount(int index){
	for(int i=index;i<discountcount-1;i++){
		discountdata[i]=discountdata[i+1];
	}
	discountdata=(struct DiscountVars*) realloc(discountdata,--discountcount*sizeof(struct DiscountVars));
}
